# -*- coding: utf-8 -*-
# article_info.py
# Created by Hardy on 5th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.

from querier.esquerier import ElasticSearchQuerier


class WechatDataOverviewQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(WechatDataOverviewQuerier, self).__init__(es, index, doc_type)

    def _build_query(self, args):
        biz_code = args.get('biz_code', None)
        from_date = args.get('from', None)
        to_date = args.get('to', None)
        filters = args.get('filters', {})
        filters = filters if filters else {}

        if biz_code is None:
            raise ValueError('biz_code is needed.')

        query = self._gen_query(biz_code, from_date, to_date, filters)
        return query, {}, {'biz_code': biz_code, 'from': from_date, 'to': to_date, 'filters': filters}

    def _build_result(self, es_result, param):
        # keywords = param['keywords']
        # order = param['order']
        total = es_result['hits']['total']
        agg = es_result['aggregations']
        return {
            'biz_code': param['biz_code'],
            'from': param['from'],
            'to': param['to'],
            'publish_count': 0 if total == 0 else agg['sum_head_count']['value'],
            'article_count': total,
            '10w_count': 0 if total == 0 else agg['sum_10w_count']['value'],
            'max_read': 0 if total == 0 else agg['max_read_num']['value'],
            'max_like': 0 if total == 0 else agg['max_like_num']['value'],
            'max_head_read': 0 if total == 0 else agg['max_head_read_num']['value'],
            'sum_read': 0 if total == 0 else agg['sum_read_num']['value'],
            'avg_read': 0 if total == 0 else agg['sum_read_num']['value'] / total,
            'sum_head_read': 0 if total == 0 else agg['sum_head_read_num']['value'],
            'avg_head_read': 0 if agg['sum_head_count']['value'] == 0 else agg['sum_head_read_num']['value'] /
                                                                           agg['sum_head_count']['value'],
            'sum_like': 0 if total == 0 else agg['sum_like_num']['value'],
            'avg_like': 0 if total == 0 else agg['sum_like_num']['value'] / total
        }

    @staticmethod
    def _gen_filter(filters, key):
        filter_clause = []
        if key in filters:
            if filters[key]:
                values = filters[key]
                if isinstance(values, str):
                    values = values.split(' ')
                for fk in values:
                    filter_clause.append({'term': {key: fk}})
        return filter_clause

    @staticmethod
    def _gen_query(biz_code, from_date, to_date, filters):
        query = {
            "query": {
                "bool": {
                    "filter": [
                        {'term': {'biz_code': biz_code}},
                        {
                            "range": {
                                "publish_timestamp": {
                                    "from": from_date,
                                    "to": to_date
                                }
                            }
                        }
                    ]
                }
            },
            "aggs": {
                "sum_read_num": {
                    "sum": {
                        "field": "read_num", "missing": 0
                    }
                },
                "max_read_num": {
                    "max": {
                        "field": "read_num", "missing": 0
                    }
                },
                "max_like_num": {
                    "max": {
                        "field": "like_num", "missing": 0
                    }
                },
                "sum_like_num": {
                    "sum": {
                        "field": "like_num", "missing": 0
                    }
                },
                "sum_head_read_num": {
                    "sum": {
                        "script": {
                            "lang": "painless",
                            "inline": "if (doc.idx.value == \"1\") {return doc.read_num.value} else {return 0}"
                        }
                    }
                },
                "max_head_read_num": {
                    "max": {
                        "script": {
                            "lang": "painless",
                            "inline": "if (doc.idx.value == \"1\") {return doc.read_num.value} else {return 0}"
                        }
                    }
                },
                "sum_head_count": {
                    "sum": {
                        "script": {
                            "lang": "painless",
                            "inline": "if (doc.idx.value == \"1\") {return 1} else {return 0}"
                        }
                    }
                },
                "sum_10w_count": {
                    "sum": {
                        "script": {
                            "lang": "painless",
                            "inline": "if (doc.read_num.value >= 100000) {return 1} else {return 0}"
                        }
                    }
                }

            },
            "size": 0
        }

        return query
